/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-05-12
 * Time: 20:41
 */
public class HashBucket {
    static class Node {
        private int key;
        private int value;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    //默认的负载因子
    private static final float DEFAULT_LOUD_FACTOR = 0.75f;
    public Node[] array;
    public int usedSize;
    public HashBucket() {
        this.array = new Node[10];
    }
    public void put(int key, int val) {
        Node node = new Node(key, val);
        int index = key % array.length;
        //遍历index下方的链表
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        //cur == null 没有这个key，头插或尾插
        node.next = array[index];
        array[index] = node;

        usedSize++;
        //扩容的时候需注意：
        //1.不能直接copy到一个新的扩容数组中，
        // 需要把原来桶中的数据一个一个拿出来，重新哈希到新数组
        if(getLoudFactor() >= DEFAULT_LOUD_FACTOR) {
            resize();
        }
    }
    private void resize() {
        //二倍扩容
        Node[] tmpArray = new Node[array.length * 2];
        //遍历原来数组下标的每个链表
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;//记录原来链表的下一个位置
                int index = cur.key % tmpArray.length;//新数组的位置
                //采用头插法放到新数组index位置
                cur.next = tmpArray[index];//这里改后，cur.next改变了
                tmpArray[index] = cur;
                cur = curNext;
            }
        }
        array = tmpArray;
    }
    private float getLoudFactor() {
        return usedSize * 1.0f / array.length;
    }
    public int getValue(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
